//
//  DrawImgService.swift
//  ReportScan
//
//  Created by woniu on 2025/7/22.
//

import Foundation
import SwiftUICore
import AppKit


class DrawImgService: NSObject {
    //签名位置坐标 尿常规、心电报告的签名位置都是这个
    private static let urineSignFrame = CGRect(x: 630, y:977, width: 120, height: 44)
    //B超签名坐标
    private static let bUltrasonicSignFrame = CGRect(x: 650, y:1037, width: 120, height: 44)
    //心电签名新坐标(华清新仪)
    public static let ecgSignFrame_new = CGRect(x: 1300, y: 170, width:140, height: 43)
    //老的，改新签名时候，需要把老签名干掉
    public static let ecgSignFrame_old = CGRect(x: 630, y:997, width: 120, height: 44)
}

extension DrawImgService{
    
    static func drawImage(reportImg:NSImage,backgroundColor: NSColor = NSColor(hexString: "#F7FCF6")!,completion: @escaping (NSImage) -> Void) {
        let size = reportImg.size
        // 创建图像
        let image = NSImage(size: size)
        // 锁定图像以进行绘制
        image.lockFocus()
        
        // 获取当前图形上下文
        guard let context = NSGraphicsContext.current?.cgContext else {
            print("无法获取图形上下文")
            return
        }
        context.scaleBy(x: 1, y: 1)
        
        
        //绘制整个背景图片
        let bgColor = backgroundColor
        let pageFrame = NSRect(x: 0, y: 0, width: size.width, height: size.height)
        drawRect(bgColor:bgColor, rect: pageFrame)
        reportImg.draw(in: pageFrame)
        
        //绘制区域
        let hrFrame = CGRect(x: 90, y: size.height-250, width: 150, height: 22)
        //给该区域填充一个背景设（擦除老的数据）
        drawRect(bgColor:.white, rect: hrFrame)
        
        
        // 2. 绘制文本
        //绘制一个红色背景
        //drawRect(bgColor: .red, rect: hrFrame)
        let text = "HR：70bpm"
        let textColor =  NSColor(hexString: "#666666")!
        getAttrStr(text: text, color: textColor, font: 16).draw(in: hrFrame)
        
        image.unlockFocus()
        completion(image)
    }
    
}

extension NSColor {
    
    /// 从十六进制字符串创建NSColor
    /// - Parameter hexString: 十六进制颜色字符串，如"F7FCF6"或"#F7FCF6"
    convenience init?(hexString: String) {
        // 移除可能存在的#号
        let cleanedString = hexString.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "#", with: "")
        
        // 检查字符串长度是否为6（RGB）
        guard cleanedString.count == 6 else {
            return nil
        }
        
        // 解析RGB分量
        let scanner = Scanner(string: cleanedString)
        var hexNumber: UInt64 = 0
        
        guard scanner.scanHexInt64(&hexNumber) else {
            return nil
        }
        
        let red = CGFloat((hexNumber & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((hexNumber & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(hexNumber & 0x0000FF) / 255.0
        
        // 创建NSColor（使用通用色彩空间）
        self.init(srgbRed: red, green: green, blue: blue, alpha: 1.0)
    }
}

extension DrawImgService{
    
    //修改姓名，性别，年龄
    static func modifyName_gender_age(reportImg:NSImage,name:String,age:Int,gender:String,completion: @escaping (NSImage) -> Void) {
        let size = reportImg.size
        // 创建图像
        let image = NSImage(size: size)
        // 锁定图像以进行绘制
        image.lockFocus()
        
        // 获取当前图形上下文
        guard let context = NSGraphicsContext.current?.cgContext else {
            print("无法获取图形上下文")
            return
        }
        context.scaleBy(x: 1, y: 1)
        
        //绘制整个背景图片
        let bgColor = NSColor(hexString: "#FFFFFF")!
        let pageFrame = NSRect(x: 0, y: 0, width: size.width, height: size.height)
        drawRect(bgColor:bgColor, rect: pageFrame)
        reportImg.draw(in: pageFrame)
        
        
        let textColor = NSColor(hexString: "#666666")!
        
        //姓名
        let nameFrame = CGRect(x: 85, y: size.height-185, width: 150, height: 25)
        //绘制一个红色背景
        //drawRect(bgColor: .red, rect: nameFrame)
        drawRect(bgColor: .white, rect: nameFrame)
        
        //性别
        let genderFrame = CGRect(x: size.width*0.5-80, y: nameFrame.minY, width: 150, height: 25)
        //绘制一个红色背景
        //drawRect(bgColor: .red, rect: genderFrame)
        drawRect(bgColor: .white, rect: genderFrame)
        
        //年龄
        let ageFrame = CGRect(x: size.width-245, y: nameFrame.minY, width: 150, height: 25)
        //绘制一个红色背景
        //drawRect(bgColor: .red, rect: ageFrame)
        drawRect(bgColor: .white, rect: ageFrame)
        
        // 2. 绘制文本
        let name = "姓名：\(name)"
        getAttrStr(text: name, color: textColor, font: 16).draw(in: nameFrame)
        
        let genderStr = "性别：\(gender)"
        getAttrStr(text: genderStr, color: textColor, font: 16).draw(in: genderFrame)
        
        let ageStr = "年龄：\(age)"
        getAttrStr(text: ageStr, color: textColor, font: 16).draw(in: ageFrame)
        
        image.unlockFocus()
        completion(image)
    }
    
    //绘制一个实心背景矩形
    public static func drawRect(bgColor:NSColor,rect:CGRect){
        let rectPath = NSBezierPath(rect: rect)
        bgColor.setFill()
        rectPath.fill()
    }
    
    public static func getAttrStr(text:String,color:NSColor,font:CGFloat)->NSAttributedString{
        // 2. 绘制文本
        let font = NSFont.systemFont(ofSize: font)
        // 设置文本属性
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor:color,
            .paragraphStyle: {
                let style = NSMutableParagraphStyle()
                style.alignment = .left
                return style
            }()
        ]
        
        // 创建富文本
        let attributedText = NSAttributedString(string: text, attributes: attributes)
        return attributedText
    }
    
}
